<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="统计周期" prop="dateRange">
        <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="部门" style="width: 220px" prop="deptId">
        <el-select
            v-model="queryParams.deptId"
            placeholder="请选择部门"
            clearable
        >
          <el-option label="全部部门" value="" />
          <el-option label="内科" value="1" />
          <el-option label="外科" value="2" />
          <el-option label="儿科" value="3" />
          <el-option label="妇产科" value="4" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['stats:dashboard:export']"
        >导出数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="RefreshLeft"
            @click="refreshData"
        >刷新</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="mb8">
      <!-- 签约人数卡片 -->
      <el-col :span="8">
        <div class="stat-card">
          <div class="stat-card-header">
            <span class="stat-card-title">签约数量</span>
            <span class="stat-card-extra text-success">
              <i class="fa fa-arrow-up"></i> 12.5%
            </span>
          </div>
          <div class="stat-card-value">{{ contractCount.toLocaleString() }}</div>
          <div class="stat-card-footer">
            <span class="text-gray-500">较上月增长</span>
            <span class="text-success ml-1">2份</span>
          </div>
        </div>
      </el-col>

      <!-- 医生人数卡片 -->
      <el-col :span="8">
        <div class="stat-card">
          <div class="stat-card-header">
            <span class="stat-card-title">医生人数</span>
            <span class="stat-card-extra text-success">
              <i class="fa fa-arrow-up"></i> 5.2%
            </span>
          </div>
          <div class="stat-card-value">{{ doctorCount.toLocaleString() }}</div>
          <div class="stat-card-footer">
            <span class="text-gray-500">较上月增长</span>
            <span class="text-success ml-1">10人</span>
          </div>
        </div>
      </el-col>

      <!-- 用户人数卡片 -->
      <el-col :span="8">
        <div class="stat-card">
          <div class="stat-card-header">
            <span class="stat-card-title">用户人数</span>
            <span class="stat-card-extra text-success">
              <i class="fa fa-arrow-up"></i> 8.7%
            </span>
          </div>
          <div class="stat-card-value">{{ userCount.toLocaleString() }}</div>
          <div class="stat-card-footer">
            <span class="text-gray-500">较上月增长</span>
            <span class="text-success ml-1">15人</span>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="12">
        <el-card shadow="always">
          <div slot="header">
            <span>数据趋势图</span>
            <el-select
                v-model="chartType"
                placeholder="请选择图表类型"
                size="mini"
                style="float: right; width: 120px"
                @change="changeChartType"
            >
              <el-option label="折线图" value="line" />
              <el-option label="柱状图" value="bar" />
            </el-select>
          </div>
          <div class="chart-container">
            <div id="trendChart" class="chart" ref="trendChart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="always">
          <div slot="header">
            <span>用户分布占比</span>
          </div>
          <div class="chart-container">
            <div id="pieChart" class="chart" ref="pieChart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card shadow="always">
      <div slot="header">
        <span>统计详情</span>
      </div>
      <el-table v-loading="loading" :data="statsList" border>
        <el-table-column label="日期" align="center" prop="date" />
        <el-table-column label="新增签约" align="center" prop="newContracts" />
        <el-table-column label="新增医生" align="center" prop="newDoctors" />
        <el-table-column label="新增用户" align="center" prop="newUsers" />
        <el-table-column label="累计签约" align="center" prop="totalContracts" />
        <el-table-column label="累计医生" align="center" prop="totalDoctors" />
        <el-table-column label="累计用户" align="center" prop="totalUsers" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button link type="primary" size="mini" @click="viewDetails(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup name="StatsDashboard">
import { onMounted, ref, reactive, toRefs, getCurrentInstance, nextTick } from 'vue'
import * as echarts from 'echarts'
// 引入后台接口方法（新增）

// 引入新增的接口
import { getContractCount, getDoctorCount, getUserCount } from '@/api/welcome/contract'


// 获取当前实例
const { proxy } = getCurrentInstance()

// 响应式数据
const contractCount = ref(0)
const doctorCount = ref(0)
const userCount = ref(0)
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const chartType = ref('line')
const trendChart = ref(null)
const pieChart = ref(null)
const statsList = ref([])

// 图表实例
let trendChartInstance = null
let pieChartInstance = null

// 表单数据
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dateRange: [],
    deptId: ''
  }
})

const { queryParams } = toRefs(data)

// 初始化图表
function initCharts() {
  // 初始化趋势图
  if (trendChart.value) {
    trendChartInstance = echarts.init(trendChart.value)
    updateTrendChart()
  }

  // 初始化饼图
  if (pieChart.value) {
    pieChartInstance = echarts.init(pieChart.value)
    updatePieChart()
  }

  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小变化
function handleResize() {
  if (trendChartInstance) {
    trendChartInstance.resize()
  }
  if (pieChartInstance) {
    pieChartInstance.resize()
  }
}

// 更新趋势图
function updateTrendChart() {
  // 伪数据
  const mockTrendData = {
    dates: ['1月', '2月', '3月', '4月', '5月', '6月'],
    contractData: [8500, 9200, 10500, 11200, 11800, 12580],
    doctorData: [650, 720, 780, 820, 860, 896],
    userData: [25000, 27500, 29800, 32000, 34200, 35680]
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['签约人数', '医生人数', '用户人数'],
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: mockTrendData.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '签约人数',
        type: chartType.value,
        data: mockTrendData.contractData,
        itemStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '医生人数',
        type: chartType.value,
        data: mockTrendData.doctorData,
        itemStyle: {
          color: '#52c41a'
        }
      },
      {
        name: '用户人数',
        type: chartType.value,
        data: mockTrendData.userData,
        itemStyle: {
          color: '#faad14'
        }
      }
    ]
  }

  trendChartInstance.setOption(option)
}

// 更新饼图
function updatePieChart() {
  // 伪数据
  const mockPieData = {
    categories: ['内科', '外科', '儿科', '妇产科', '骨科', '其他'],
    values: [320, 180, 120, 95, 85, 96]
  }

  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      top: 'center'
    },
    series: [
      {
        name: '医生科室分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: mockPieData.categories.map((category, index) => ({
          name: category,
          value: mockPieData.values[index]
        }))
      }
    ]
  }

  pieChartInstance.setOption(option)
}

// 切换图表类型
function changeChartType() {
  updateTrendChart()
}

// 获取统计数据
function getList() {
  loading.value = true;

  // 并行调用三个接口：签约人数、医生人数、用户人数
  Promise.all([
    getContractCount(),   // 签约人数接口
    getDoctorCount(),     // 医生人数接口
    getUserCount()        // 用户人数接口
  ])
      .then(([contractRes, doctorRes, userRes]) => {
        // 从接口获取真实数据
        const realContractCount = contractRes.data;
        const realDoctorCount = doctorRes.data;
        const realUserCount = userRes.data;

        // 赋值给响应式变量
        contractCount.value = realContractCount;
        doctorCount.value = realDoctorCount;
        userCount.value = realUserCount;

        // 统计列表数据（基于真实数据计算）
        statsList.value = [
          {
            date: '2023-06-15',
            newContracts: 128,
            newDoctors: 12,
            newUsers: 356,
            totalContracts: realContractCount, // 真实签约总数
            totalDoctors: realDoctorCount,     // 真实医生总数
            totalUsers: realUserCount          // 真实用户总数
          },
          {
            date: '2023-06-14',
            newContracts: 95,
            newDoctors: 8,
            newUsers: 289,
            totalContracts: realContractCount - 128, // 递减计算前一天累计
            totalDoctors: realDoctorCount - 12,
            totalUsers: realUserCount - 356
          },
          {
            date: '2023-06-13',
            newContracts: 112,
            newDoctors: 5,
            newUsers: 312,
            totalContracts: realContractCount - 128 - 95,
            totalDoctors: realDoctorCount - 12 - 8,
            totalUsers: realUserCount - 356 - 289
          },
          {
            date: '2023-06-12',
            newContracts: 87,
            newDoctors: 3,
            newUsers: 245,
            totalContracts: realContractCount - 128 - 95 - 112,
            totalDoctors: realDoctorCount - 12 - 8 - 5,
            totalUsers: realUserCount - 356 - 289 - 312
          },
          {
            date: '2023-06-11',
            newContracts: 105,
            newDoctors: 6,
            newUsers: 298,
            totalContracts: realContractCount - 128 - 95 - 112 - 87,
            totalDoctors: realDoctorCount - 12 - 8 - 5 - 3,
            totalUsers: realUserCount - 356 - 289 - 312 - 245
          }
        ];

        total.value = 30; // 模拟总条数
      })
      .catch(error => {
        console.error('获取数据失败:', error);
        // 接口失败时使用默认模拟数据
        contractCount.value = 12580;
        doctorCount.value = 896;
        userCount.value = 35680;

        // 恢复默认列表数据
        statsList.value = [
          {
            date: '2023-06-15',
            newContracts: 128,
            newDoctors: 12,
            newUsers: 356,
            totalContracts: 12580,
            totalDoctors: 896,
            totalUsers: 35680
          },
          {
            date: '2023-06-14',
            newContracts: 95,
            newDoctors: 8,
            newUsers: 289,
            totalContracts: 12452,
            totalDoctors: 884,
            totalUsers: 35324
          },
          {
            date: '2023-06-13',
            newContracts: 112,
            newDoctors: 5,
            newUsers: 312,
            totalContracts: 12357,
            totalDoctors: 876,
            totalUsers: 35035
          },
          {
            date: '2023-06-12',
            newContracts: 87,
            newDoctors: 3,
            newUsers: 245,
            totalContracts: 12245,
            totalDoctors: 871,
            totalUsers: 34723
          },
          {
            date: '2023-06-11',
            newContracts: 105,
            newDoctors: 6,
            newUsers: 298,
            totalContracts: 12158,
            totalDoctors: 868,
            totalUsers: 34478
          }
        ];
        total.value = 30;
      })
      .finally(() => {
        loading.value = false;
        // 接口请求完成后更新图表（确保图表使用最新数据）
        updateTrendChart();
      });
}

// 搜索
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 刷新数据
// 刷新方法也同步修改，同时刷新三个数据
// 刷新方法也同步修改，同时刷新三个数据
function refreshData() {
  loading.value = true;
  Promise.all([getContractCount(), getDoctorCount(), getUserCount()])
      .then(([contractRes, doctorRes, userRes]) => {
        contractCount.value = contractRes.data;
        doctorCount.value = doctorRes.data;
        userCount.value = userRes.data;
        updateTrendChart();
        proxy.$modal.msgSuccess("数据已刷新");
      })
      .catch(() => {
        proxy.$modal.msgError("刷新失败");
      })
      .finally(() => {
        loading.value = false;
      });
}

// 查看详情
function viewDetails(row) {
  proxy.$modal.info({
    title: '详情',
    content: `
      <div style="text-align: left;">
        <p>日期: ${row.date}</p>
        <p>新增签约: ${row.newContracts}人</p>
        <p>新增医生: ${row.newDoctors}人</p>
        <p>新增用户: ${row.newUsers}人</p>
        <p>累计签约: ${row.totalContracts}人</p>
        <p>累计医生: ${row.totalDoctors}人</p>
        <p>累计用户: ${row.totalUsers}人</p>
      </div>
    `
  })
}

// 导出数据
function handleExport() {
  proxy.download('stats/dashboard/export', {
    ...queryParams.value
  }, `stats_dashboard_${new Date().getTime()}.xlsx`)
}

// 页面挂载时初始化
onMounted(() => {
  nextTick(() => {
    initCharts()
    getList()
  })
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (trendChartInstance) {
    trendChartInstance.dispose()
  }
  if (pieChartInstance) {
    pieChartInstance.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.stat-card {
  background: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.stat-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.stat-card-title {
  font-size: 14px;
  color: #666;
}

.stat-card-extra {
  font-size: 12px;
}

.stat-card-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.stat-card-footer {
  font-size: 12px;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.chart {
  width: 100%;
  height: 100%;
}

::v-deep .el-card__body {
  padding: 16px;
}

.text-gray-500 {
  color: #909399;
}

.text-success {
  color: #52c41a;
}
</style>
